﻿CREATE PROCEDURE [dbo].[OrderLinesInsert]
(--Заказ товара у поставщика
	@Id int out,					-- Добавлен mf 14.09.2006 17:15
	@DocId int,
	@GoodsVsContragentsId int,
	@GoodsId int,
	@Qntty int,		
	@QnttySum decimal(19, 2),
	@Note varchar(250),
	@MD datetime out,				-- Исправлен на output mf 14.09.2006 17:15
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
DECLARE @intDocTypeId int

SET NOCOUNT ON
IF (@DocId Is Null) OR (@GoodsVsContragentsId Is Null) OR (@QnttySum Is Null) OR (@Qntty Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <= 0) OR (@QnttySum <= 0)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Количество и сумма д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intDocTypeId = DocTypeId
FROM [CA].[Documents] WHERE Id = @DocId
IF (@intDocTypeId Is Null)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Не найден документ с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 11)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Неправильный тип документа с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF @GoodsId Is Null SELECT @GoodsId = GoodsId FROM CA.GoodsVsContragents WHERE Id = @GoodsVsContragentsId

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @Id OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;

INSERT INTO CD.ManageDocLines
(Id, [DocId], GoodsVsContragentsId, [GoodsId], Qntty, QnttySum, 
[Note], [MD], [MW]) 
VALUES (@Id, @DocId, @GoodsVsContragentsId, @GoodsId, @Qntty, @QnttySum,
@Note, @MD, @MW);

-- Удалено mf 14.09.2006 17:15
--SELECT Id, [DocId], GoodsVsContragentsId, [GoodsId], Qntty, QnttySum, 
--[Note], [MD], [MW]
--FROM CD.ManageDocLines WHERE Id = SCOPE_IDENTITY()
--select @Id = scope_identity()	-- Добавлен mf 14.09.2006 17:15
RETURN 0

